const http = require('http'),
      express = require('express'),
      app = express(),
      // mysql = require('mysql'),
      domain = require('domain'),
      iconv = require('iconv-lite'),
      cp = require('child_process'),
      files = require('./files.js'),
      router1 = require('./router1.js')
    // cookieParser = require('cookie-parser');
// require('babel-register');//解析es6的，待研究
const server = http.createServer(app);
// var pool=mysql.createPool({
//  host:'localhost',
//  user:'root',
//  password:'123456',
//  database:'mysite'
//  // port:3306
// });
function getClientIP(req) {
    let ipAddress;  
    let forwardedIpsStr=req.header('x-forwarded-for');
    if(forwardedIpsStr){// 判断是否有反向代理 IP
        let forwardedIps=forwardedIpsStr.split(',');
        ipAddress=forwardedIps[0];
    }
    if (!ipAddress){  
        ipAddress=req.connection.remoteAddress||// 判断 connection 的远程 IP
                req.socket.remoteAddress|| // 判断后端的 socket 的 IP
                req.connection.socket.remoteAddress||
                req.headers['remote_addr']||
                req.headers['client_ip']||
                req.ip;
    } 
    return ipAddress
};
// pool.connect=function(myquery,myfunc,arr=null){
//  return new Promise(function(resolve,reject){
//      pool.getConnection((error,connection)=>{
//          if(error){
//              console.log("建立连接失败");
//              reject(error);
//          }else{
//              console.log("建立连接成功");
//              // console.log("连接数:"+pool._allConnections.length);
//              let data;
//              connection.query(myquery,arr,(err,rows)=>{
//                  data=myfunc(err,rows);
//                  // console.log("连接数:"+pool._allConnections.length);
//                  if(err){
//                      reject(err);
//                      connection.release();
//                  }else{
//                      resolve(data);
//                      connection.release();
//                  }
//              });
//          }
//      });
//  });
// };
Date.prototype.Format = function(fmt){
    var o = {
        "M+" : this.getMonth()+1,
        "d+" : this.getDate(),
        "h+" : this.getHours(),
        "m+" : this.getMinutes(),
        "s+" : this.getSeconds(),
        "q+" : Math.floor((this.getMonth()+3)/3),
        "S"  : this.getMilliseconds()
    };   
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
    for(var k in o){
        if(new RegExp("("+ k +")").test(fmt))   
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
    }
    return fmt;   
}

function getIPAdress(){  
    var interfaces = require('os').networkInterfaces();  
    for(var devName in interfaces){  
        var iface = interfaces[devName];  
        for(var i=0;i<iface.length;i++){  
           var alias = iface[i];  
           if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){
                return alias.address;  
            }  
        }  
    }  
}

// app.engine('html', require('expres-art-template'))待研究？
app.use('/', files);
app.use('/', router1);

app.get('*', function(req, res) {
    res.sendFile('./404.html');
});

// // return next(err)
app.use(function (err, req, res, next) {
    // 带有四个参数的 middleware 专门用来处理异常
    console.error(err);
    res.status(500);
    res.json({
        code: -1,
        data: null,
        message: '程序异常',
        success: false
    })
});

// 使用 domain 来捕获大部分异常
// app.use(function (req, res, next) {
//     let reqDomain = domain.create();
//     reqDomain.on('error', function () {
//         try {
//             let killTimer = setTimeout(function () {
//                 process.exit(1);
//             }, 30000);
//             killTimer.unref();
//             server.close();
//             res.send(500);
//         }catch(e) {
//             console.log('error when exit', e.stack);
//         }
//     });

//     reqDomain.run(next);
// });

process.on('unhandledRejection', (err,p) => {
    console.error('Error:', err);
})//捕获promise未处理的异常

process.on('uncaughtException', (err) => {
    console.error('Error2:', err);
    try {
        let killTimer = setTimeout(function () {
            process.exit(1);
        }, 30000);
        killTimer.unref();

        server.close();
    }catch (e) {
        console.log('error when exit', e.stack);
    }
})//捕获node未处理的异常

var host, port;
server.listen(3003, getIPAdress(), () => {
    host = server.address().address;
    port = server.address().port;
    console.log("访问地址为http://%s:%s", host, port);
    // cp.exec(`start C:\\"Program Files (x86)"\\Google\\Chrome\\Application\\chrome.exe http://${host}:${port}`);
})
// server.listen(80, 'localhost', () => {
//     host = server.address().address;
//     port = server.address().port;
//     console.log("访问地址为http://%s:%s", host, port);
//     // cp.exec(`start C:\\"Program Files (x86)"\\Google\\Chrome\\Application\\chrome.exe http://${host}:${port}`);
//     cp.exec(`start C:\\"Program Files (x86)"\\Google\\Chrome\\Application\\chrome.exe http://localhost`);
// })